
#include <board.h>
#include <rtdevice.h>
#include <drivers/i2c.h>

#ifdef RT_USING_I2C

#define DBG_LVL               DBG_LOG

#define DBG_TAG               "test_i2c_24c02"
#include <rtdbg.h>

#define I2C_DEVICE			"i2c1"
#define DATA_LEN			16

//static uint8_t buff_w[DATA_LEN];
static struct rt_i2c_bus_device *i2c_bus;

int test_i2c_24c02() {

	rt_uint16_t slave_addr = 0x50; // 1010 00 0

	uint8_t begin_addr = 0x00;

	uint8_t buff_r[DATA_LEN] = { 0 };

	i2c_bus = (struct rt_i2c_bus_device*) rt_device_find(I2C_DEVICE);

	if (i2c_bus == RT_NULL) {
		LOG_E("can't find '%s' device", I2C_DEVICE);
		return -1;
	}

	rt_size_t ret;

	// Single Byte Write
	for (int i = 1; i < DATA_LEN; i++) {

		uint8_t data[] = { i, i + 1 }; // {内存地址, 要写的一个字节数据}

		ret = rt_i2c_master_send(i2c_bus, slave_addr, RT_I2C_WR, data, 2);
		if (ret != 2) {
			LOG_E("rt_i2c_master_send failed, ret: %d", ret);
			return -RT_ERROR;
		}
		rt_thread_mdelay(5);
	}

	LOG_I("single byte write eeprom ok\n");

//	// Multiple Bytes Write
//	buff_w[0] = 0x00;
//
//	for (int i = 0; i < DATA_LEN; i++) {
//		buff_w[i] = i;
//	}

//	struct rt_i2c_msg msgs_w[] = { { slave_addr, RT_I2C_WR, 1, &begin_addr }, {
//			slave_addr, RT_I2C_NO_START | RT_I2C_WR, DATA_LEN, buff_w } };
//
//	ret = rt_i2c_transfer(i2c_bus, msgs_w, ARRAY_SIZE(msgs_w));
//
//	if (ret != ARRAY_SIZE(buff_w)) {
//		LOG_E("writing data failed, ret: %d", ret);
//		return -RT_ERROR;
//	}

	LOG_I("multiple bytes write eeprom ok\n");
	rt_thread_mdelay(10);

	// Single Byte Read
	// 立即地址读
	ret = rt_i2c_master_send(i2c_bus, slave_addr, RT_I2C_WR, &begin_addr, 1); // 写 要读的地址
	if (ret != 1) {
		LOG_E("writing address to read failed, ret: %d", ret);
		return -RT_ERROR;
	}
	for (uint8_t i = 0; i < DATA_LEN; i++) {
		ret = rt_i2c_master_recv(i2c_bus, slave_addr, RT_I2C_RD, buff_r + i, 1); // 读 数据
		if (ret != 1) {
			LOG_E("writing data failed, ret: %d", ret);
			return -RT_ERROR;
		}
		LOG_I("[%02d]: 0x%x", i, buff_r[i]);
	}

	LOG_I("single byte read eeprom ok\n");

	// Multiple Bytes Read
	rt_memset(buff_r, 0, DATA_LEN);

	struct rt_i2c_msg msgs[] = { { slave_addr, RT_I2C_WR, 1, &begin_addr }, {
			slave_addr, RT_I2C_RD, DATA_LEN, buff_r } };

	ret = rt_i2c_transfer(i2c_bus, msgs, ARRAY_SIZE(msgs));

	if (ret < 0) {
		LOG_E("rt_i2c_transfer failed, ret: %d", ret);
		return -2;
	}

	for (uint8_t i = 0; i < DATA_LEN; i++) {
		LOG_I("[%02d]: %02d", i, buff_r[i]);
	}

	LOG_I("multiple bytes read eeprom ok\n");

	return 0;
}

MSH_CMD_EXPORT(test_i2c_24c02, test i2c_24c02);
//INIT_APP_EXPORT(test_i2c_fm24v10);

#endif // RT_USING_I2C

